from django.forms.models import model_to_dict
from BloodSpiderAPI.models import PhoneNumber, PhoneNumberOrder


# 模型转字典
def utils_model_to_dict(model, *args, **kwargs):
    """
    将Django模型对象转换为字典，处理UUID和时间字段
    
    参数:
        model: Django模型实例
        *args, **kwargs: 其他传递给model_to_dict的参数
        show_time: 是否显示时间字段
    
    返回:
        dict: 转换后的字典数据
    """
    data = model_to_dict(model, *args, **kwargs)
    
    # 转换UUID类型的字段为字符串
    if hasattr(model, 'phone_number_id'):
        data["phone_number_id"] = str(model.phone_number_id)
    if hasattr(model, 'phone_order_id'):
        data["phone_order_id"] = str(model.phone_order_id)
    if hasattr(model, 'phone_number'):
        data["phone_number_id"] = str(model.phone_number.phone_number_id)
        data["phone"] = model.phone_number.phone
        data["name"] = model.phone_number.name
        
    # 处理时间格式
    if kwargs.get("show_time", True):
        if hasattr(model, 'create_time'):
            data["create_time"] = model.create_time.strftime("%Y-%m-%d %H:%M:%S")
        if hasattr(model, 'update_time'):
            data["update_time"] = model.update_time.strftime("%Y-%m-%d %H:%M:%S")
    
    return data


# 获取手机号详情（包含关联订单）
def get_phone_number_detail(phone_number_id):
    """
    获取手机号详情及其关联的订单信息
    
    参数:
        phone_number_id: 手机号ID
    
    返回:
        dict: 包含手机号详情和关联订单的字典
    """
    try:
        phone_number = PhoneNumber.objects.get(phone_number_id=phone_number_id)
        phone_data = utils_model_to_dict(phone_number)
        
        # 获取关联的手机订单
        phone_orders = PhoneNumberOrder.objects.filter(phone_number=phone_number_id) or []
        phone_data['phone_orders'] = [utils_model_to_dict(order) for order in phone_orders]
        
        return phone_data
    except PhoneNumber.DoesNotExist:
        return None


# 获取手机号订单详情
def get_phone_order_detail(phone_order_id):
    """
    获取手机号订单详情
    
    参数:
        phone_order_id: 手机号订单ID
    
    返回:
        dict: 手机号订单详情字典
    """
    try:
        phone_order = PhoneNumberOrder.objects.get(phone_order_id=phone_order_id)
        return utils_model_to_dict(phone_order)
    except PhoneNumberOrder.DoesNotExist:
        return None